<template>
  <div class="bookcase">
    <div class="reading" v-if="isRead">
      <div class="content">
        <div class="chapter" v-if="hasChapter">
          <div v-for="(x, y) in chapters" :key="y" @click="selectChpater(y)" :class="chapterIdx == y ? 'active' : ''">
            {{ x }}
          </div>
        </div>
        <template v-if="hasChapter">
          <div class="story" style="width: calc(100% - 200px);">
            <h1>{{ chapters[chapterIdx] + ' ' + storys[chapterIdx][0] }}</h1>
            <div v-for="(x, y) in storys[chapterIdx]" :key="y" @click="selectTxt(y)"
              :class="storyIdx == y ? 'active' : ''" :style="{ fontSize: fontSize + 'px' }">
              {{ x }}
            </div>
          </div>
        </template>
        <template v-else>
          <div class="story" style="width: 100%">
            <div>
              {{ menu[menuIdx] + ' > ' + list[listIdx] + ' > ' + books[bookIdx] }}
            </div>
            <h1>{{ books[bookIdx].split('.')[0] }}</h1>
            <div v-for="(x, y) in storys" :key="y" @click="selectTxt(y)" :class="storyIdx == y ? 'active' : ''">
              {{ x }}
            </div>
          </div>
        </template>
        <div class="control">
          <!-- <div ref="audio"></div> -->
          <div class="isset" v-if="!isSet" @click="showSet">
            <span class="iconfont icon-shezhi"></span>
          </div>
          <div v-else class="control-con">
            <div>{{ books[bookIdx].split('.')[0] }}</div>
            <div>
              <div @click="openRead">
                <span v-if="canRead == false">阅读</span>
                <span v-else>停止</span>
              </div>
              <div>设置</div>
              <div @click="addSize"> 加大 </div>
              <div @click="reduceSize"> 减小 </div>
              <div @click="goPath">打开</div>
              <div @click="cancleRead">返回</div>
              <div @click="showSet">隐藏</div>
            </div>
          </div>
          <!-- <div @click="openRead">
            <span v-if="canRead == false">阅读</span>
            <span v-else>停止</span>
          </div>
          <div>设置</div>
          <div @click="goPath">打开</div>
          <div class="close" @click="cancleRead">返回</div> -->
        </div>
      </div>
    </div>
    <div class="noread" v-else>
      <div class="menu">
        <div v-for="(x, y) in menu" :key="y" @click="selectMenu(y)" :class="menuIdx == y ? 'active' : ''">
          {{ x }}
        </div>
      </div>
      <div class="list">
        <div v-for="(x, y) in list" :key="y" @click="selectList(y)" :class="listIdx == y ? 'active' : ''">
          {{ x }}
        </div>
      </div>
      <div class="book">
        <div v-for="(x, y) in books" :key="y" @click="selectBook(y)" :class="bookIdx == y ? 'active' : ''">
          <div class="line"></div>
          <div class="book-name">{{ x.split('.')[0] }}</div>
          <div v-if="bookIdx == y" @click="openBook" class="open">阅读</div>
        </div>
      </div>
      <div>
        <el-button @click="addList">添加分类</el-button>
        <el-button @click="editList">编辑分类</el-button>
        <el-button @click="addBook">添加书本</el-button>
        <el-button @click="editBook">编辑书本</el-button>
      </div>
    </div>
    <el-dialog v-model="show" :title="title" width="600">
      <el-form>
        <el-form-item label="输入名称">
          <el-input v-model="keyword" style="width: 600px;" @keyup.enter="submit"></el-input>
        </el-form-item>
        <el-form-item label="输入内容" v-if="formType == 3">
          <el-input type="textarea" :rows="10" v-model="content" style="width: 600px;" @keyup.enter="submit"></el-input>
        </el-form-item>
        <el-button @click="submit">确认</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, nextTick } from 'vue'
import system from '@/utils/system';
import element  from '@/utils/element';
import { queryData } from '@/apis/mysql';
const menu = ref([])
const menuIdx = ref(0)
const isRead = ref(false)
const canRead = ref(false)
const show = ref(false)
const hasChapter = ref(false)
const reload = ref(false)
const isSet = ref(false)
const books = ref([])
const list = ref([])
const listIdx = ref(0)
const bookIdx = ref(0)
const count = ref(0)
const editWord = ref([])
const chapters = ref([])
const storys = ref([])
const storyIdx = ref([])
const chapterIdx = ref(0)
const formType = ref(1)
const reg = ref('')
const title = ref('')
const keyword = ref('')
const content = ref('')
const fontSize = ref(24)
onMounted(() => {
  getPath()
})

let bookPath = ''
function getPath() {
  queryData({
    table: 'resources',
    data: {
      name: 'novel'
    }
  }).then((res) => {
    let obj = res.data[0]
    bookPath = `${obj.disk}:/${obj.path}`
    // document.title = obj.title
    getMenu()
  })
}

function getMenu() {
  system.readDir(bookPath).then(res => {
    menu.value = res
    selectMenu(0)
  })
}

function localDir() {
  return bookPath + '/' +
    menu.value[menuIdx.value] + '/' +
    list.value[listIdx.value] + '/' +
    books.value[bookIdx.value]
}

function showSet() {
  isSet.value = !isSet.value
}

// 选择目录
function selectMenu(y) {
  menuIdx.value = y
  system.readDir(bookPath + '/' + menu.value[y]).then(res => {
    if (res.length == 0) {
      list.value = []
      books.value = []
    } else {
      list.value = res
      listIdx.value = 0
      selectList(0)
    }
  })
}

// 选择分类
function selectList(y) {
  listIdx.value = y
  let dir = bookPath + '/' + menu.value[menuIdx.value] + '/' + list.value[y]
  bookIdx.value = 0
  system.readDir(dir).then(res => {
    if (res.length == 0) {
      books.value = []
      count.value = 0
    } else {
      books.value = res
    }
  })
}

function selectBook(y) {
  bookIdx.value = y
  if (menuIdx.value == 0) {
    readBookContent(y)
  }
}

function readBookContent(y) {
  bookIdx.value = y
  let dir = localDir()
  system.readFile(dir).then(res => {
    editWord.value = res
  })
}

// 检索章节目录
function txtCharpter(string) {
  let regList = [
    /第(\S*)章\s+/g,
    /第(\S+)回\s+/g,
    /第(\S+)卷\s+/g,
    /第(\S+)卦\s+/g
  ]
  let arr = []
  if (string.match(regList[0])) {
    arr = string.match(regList[0])
    reg.value = regList[0]
  }else if(string.match(regList[1])){
    arr = string.match(regList[1])
    reg.value = regList[1]
  }else if(string.match(regList[2])){
    arr = string.match(regList[2])
    reg.value = regList[2]
  }else{
    arr = string.match(regList[3])
    reg.value = regList[3]
  }
  return arr
}

// 检索章节内容
function txtSentence(string) {
  let list = []
  let arr = string.split(reg.value)
  arr.map((x, y) => {
    if (y % 2 == 0) {
      list.push(x)
    }
  })
  return list.slice(1)
}

// 打开书本
function openBook() {
  let dir = localDir()
  system.readFile(dir).then(res => {
    let list = []
    let content = res.toString('utf8')
    let list1 = txtCharpter(content)
    if (Array.isArray(list1)) {
      isRead.value = true
      hasChapter.value = true
      chapterIdx.value = 0
      chapters.value = list1
      let arr = txtSentence(content)
      // // console.log(story)
      arr.map((x, y) => {
        list.push([])
        x.split('\n').map(a => {
          if (a != '\r') {
            list[y].push(a)
          }
        })
      })
      storys.value = list
    } else {
      // // console.log(res)
      const content = res.toString('utf8')
      // const content = ansiToUtf8(res);
      // // console.log(content)
      isRead.value = true
      chapterIdx.value = 0
      hasChapter.value = false
      chapters.value = ['无章节']
      storys.value = content.split('\n')
      // const list = []
      // content.map((x, y) => {
      //   if (y % 2 == 0) {
      //     list.push(x)
      //   }
      // })
      // // // console.log(story)
      // alert('该书籍需要进行处理才能显示！')txtSentence
    }
  })
}

// 选择文字
function selectTxt(y) {
  if (canRead.value == true) {
    storyIdx.value = y
    //sepak(story[chapterIdx][y])
  }
}

// 选择章节
function selectChpater(y) {
  chapterIdx.value = y
  storyIdx.value = -1
  reload.value = true
  nextTick(() => {
    reload.value = false
    backTop()
  })
}


// 返回顶部
function backTop() {
  document.body.scrollTop = 0
  document.documentElement.scrollTop = 0
}
// 取消阅读
function cancleRead() {
  isRead.value = false
}

function goPath() {
  system.openFile(localDir())
}

function addList() {
  title.value = "添加列表"
  show.value = true
  formType.value = 1
  keyword.value = ''
}

function editList() {
  title.value = "修改列表"
  show.value = true
  formType.value = 2
  keyword.value = list.value[listIdx.value]
}

function addBook() {
  title.value = "添加书籍"
  show.value = true
  formType.value = 3
  keyword.value = ''
}

function editBook() {
  title.value = "修改书籍"
  show.value = true
  formType.value = 4
  keyword.value = books.value[bookIdx.value]
}


function submit() {
  if (formType.value == 1) {
    const path = bookPath + '/' + menu.value[menuIdx.value] + '/' + keyword.value
    system.addDir(path).then((res) => {
      if (res == null) {
        element.success('创建成功！')
        show.value = false
        selectMenu(menuIdx.value)
      } else {
        element.error('创建失败！')
      }
    })
  } else if (formType.value == 2) {
    const newPath = bookPath + '/' + menu.value[menuIdx.value] + '/' + keyword.value
    let old = bookPath + '/' + menu.value[menuIdx.value] + '/' + list.value[listIdx.value]
    system.rename(old, newPath).then((res) => {
      if (res == null) {
        element.success('修改成功！')
        show.value = false
        selectMenu(menuIdx.value)
      } else {
        element.error('修改失败！')
      }
    })
  } else if (formType.value == 3) {
    const path = bookPath + '/' + menu.value[menuIdx.value] + '/' + list.value[listIdx.value] + '/' + keyword.value + '.txt'
    system.writeFile(path, content.value).then((res) => {
      if (res == null) {
        element.success('创建成功！')
        show.value = false
        selectList(listIdx.value)
      } else {
        element.error('创建失败！')
      }
    })
  } else if (formType.value == 4) {
    const newPath = bookPath + '/' + menu.value[menuIdx.value] + '/' + list.value[listIdx.value] + keyword.value + '.txt'
    let old = localDir()
    system.rename(old, newPath).then((res) => {
      if (res == null) {
        element.success('修改成功！')
        show.value = false
        selectList(listIdx.value)
      } else {
        element.error('修改失败！')
      }
    })
  }
}

function addSize() {
  fontSize.value++;
}

function reduceSize() {
  fontSize.value--;
}
</script>

<style lang="scss" scoped>
.bookcase {
  width: 100%;
  height: 100%;
}

.noread {
  width: calc(100% - 40px);
  height: calc(100% - 40px);
  padding: 20px;

  .menu {
    width: 100%;
    height: 40px;
    display: flex;

    >div {
      width: 120px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      cursor: pointer;
      user-select: none;
    }

    .active {
      color: #fff;
      background-color: #21e7d4;
    }
  }

  .list {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    div {
      margin: 10px;
      border-radius: 10px;
      width: 150px;
      height: 60px;
      line-height: 60px;
      cursor: pointer;
      user-select: none;
      text-align: center;
      background-color: #ffe87f;
      color: #000;
    }

    .active {
      color: #f00;
    }

    .add {
      font-size: 24px;
      font-weight: 700;
    }
  }

  .book {
    width: 100%;
    overflow: auto;
    margin-bottom: 20px;
    display: flex;
    flex-wrap: wrap;

    >div {
      margin: 10px;
      width: 100px;
      height: 140px;
      //padding: 20px 6px;
      background-color: #2f4d7d;
      cursor: pointer;
      user-select: none;
      text-align: center;
      position: relative;

      .line {
        width: 2px;
        height: 100%;
        background-color: #fff;
        position: absolute;
        bottom: 0;
        left: 6px;
      }

      .book-name {
        width: 80px;
        line-height: 30px;
        color: #fff;
        font-weight: 700;
        position: absolute;
        top: 20px;
        font-size: 18px;
        left: 15px;
      }

      >div {
        width: calc(100% - 12px);
        height: 24px;
        line-height: 24px;
        bottom: 10px;
        left: 6px;
        color: #ccc;
        border-radius: 12px;
        position: absolute;

        &.open {
          color: #fff;
          font-weight: 700;

          &:hover {
            color: #000;
            background-color: #fff;
          }
        }
      }
    }

    .active {
      font-weight: 700;
      background-image: linear-gradient(to right bottom, #5315ff, #e6c0ff);
    }
  }
}

.reading {
  width: 100%;
  height: 100%;
  position: relative;

  .content {
    height: 100%;
    display: flex;

    .chapter {
      width: 200px;
      height: 100%;
      overflow: auto;

      div {
        width: 100%;
        height: 40px;
        line-height: 40px;
        cursor: pointer;
        text-indent: 20px;
      }

      .active {
        color: #f00;
      }
    }

    .story {
      height: calc(100vh - 40px);
      padding: 20px;
      overflow: auto;

      h1 {
        width: 100%;
        height: 60px;
        line-height: 60px;
        text-align: center;
      }

      div {
        text-indent: 30px;
        margin-bottom: 20px;
        cursor: pointer;
      }


      .active {
        color: #f00;
      }
    }
  }

  .control {
    width: 40px;
    height: 40px;
    position: absolute;
    // border-radius: 50%;
    bottom: 10px;
    right: 10%;

    // background-color: rgba(0, 0, 0, 0.5);
    .isset {
      width: 100%;
      height: 100%;
      color: #000;
      background-color: #ffe87f;
      // overflow: hidden;
      border-radius: 50%;
      cursor: pointer;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 48px;
      font-weight: 700;
    }

    .control-con {
      width: 600px;
      position: absolute;
      display: flex;
      right: 40px;
      background-color: #ffe87f;
      color: #000;

      >div:first-child {
        width: 200px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        // margin-top: 20px;
      }

      >div:last-child {
        // width: 100%;
        display: flex;
        //flex-wrap: wrap;

        >div {
          // width: 25%;
          height: 40px;
          padding: 0 10px;
          cursor: pointer;
          user-select: none;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }
}

.write {
  width: calc(100% - 100px);
  overflow: auto;
  padding: 0 50px;

  div {
    float: left;
    margin: 10px;
  }

  button {
    width: 100px;
  }

  input {
    width: 150px;
    height: 36px;
    text-indent: 12px;
  }
}
</style>
